import React, { useState, useEffect } from 'react';
import FormItem from '../../../components/FormItem';
import {
  Form,
  Input,
  Button,
  message,
  InputNumber,
  Radio,
  Row,
  Col,
  Select,
  Divider,
  Checkbox,
  Switch,
  Icon,
} from 'antd';

import { connect } from 'react-redux';
import services from '../../../services/api';
import {
  CALCULATE_CODE_GROUP,
  CONDITION_TYPE,
  IS_EXEC_CONDITION,
  DATA_SOURCE_TYPE,
  ENABLE_STATUS,
  GLOBAL_TRUE_FALSE,
  VARIABLE_TYPE,
} from '../../../utils/constant';
import AddConditions from './AddConditions';
import useVariableData from '../../../hook/useVariableData';
import Preview from './Preview';
import Question from '../../../components/Question';
import { getChildTimeUnit } from 'src/utils/utils';
import { getConditionGroupJson } from '../../../utils/json/index';
import { compare, compareClass } from '../../../utils/compare';
import useAppProductEventData from 'src/hook/useAppProductEventData';

function IndicatorAdd(props) {
  const {
    app_id,
    event_id,
    event_name,
    product_id,
    feature_name,
    data_source_type,
    data_source_id,
    source_name,
    remark,
    date_range,
    date_range_unit,
    calculate_type_id,
    calculate_field,
    main_field,
    main_field_name,
    sec_field,
    sec_field_name,
    duration_time_unit,
    duration_time,
    is_contains_this,
    limit_count,
    sort_type,
    is_exec_condition = 0,
    condition_type,
    status,
    calculate_accuracy,
    calculate_accuracy_unit,
    is_history,
    trend_direction,
    using_variables,
    calculate_field_name
  } = props.value || {};
  const [senior, setSenior] = useState(false);
  const [dataSources, setDataSources] = useState([]);
  const [calculate, setCalculate] = useState([]);
  const [accuracyUnit, setAccuracyUnit] = useState([]);
  const [calculateRemark, setCalculateRemark] = useState(''); //计算方式的当前remark
  const [contitionType, setConditionType] = useState(
    props.value && props.value.condition_type ? props.value.condition_type : CONDITION_TYPE._CONFIG
  );
  const [conditions, setCondition] = useState(
    props.value && props.value.condition_type && props.value.condition_type === CONDITION_TYPE._CONFIG
      ? props.value.conditions
      : []
  );
  const [conditionText, setConditionText] = useState(
    props.value && props.value.condition_type && props.value.condition_type === CONDITION_TYPE._SQ
      ? props.value.conditions
      : ''
  );
  const [calculateField, setCalculateField] = useState([]); // 计算字段限制结果，有问题待解决
  console.log(calculateField)
  const [isNature, setIsNature] = useState(false);

  const { items, appId, eventId, productId } = useAppProductEventData({
    ...props,
    app_id,
    event_id,
    event_name,
    product_id,
    disabled: props.actionType !== 'add' && props.actionType !== 'copy',
    form: props.form,
    layout: {
      className: 'tantuer-form-item3 tantuer-form-item-nowrap',
    },
    onAppChange: onAppOrEventIdHandleChange.bind(this, 'app_id'),
    onProductChange: onAppOrEventIdHandleChange.bind(this, 'product_id'),
    onEventChange: onAppOrEventIdHandleChange.bind(this, 'event_id'),
  });

  const variable = useVariableData({
    limitType: [VARIABLE_TYPE._FIELD, VARIABLE_TYPE._LITERAL],
    appId,
    eventId,
  }); //字段添加页，默认需要字段、指标的变量
  const time_codes = props.window_time_unit || []; // 时间码表
  // const dataSourceType = 1;

  const NATURE_TIME_KEYS = [6, 7, 8, 9, 10];
  const form = props.form;
  useEffect(() => {
    getCalculate(); //获取计算方式

    // 非添加的时候
    if (props.value && props.value.app_id) {
      const { calculate_accuracy, calculate_accuracy_unit } = props.value;

      if (NATURE_TIME_KEYS.includes(props.value.date_range_unit)) {
        setIsNature(true);
      } else {
        setIsNature(false);
      }
      if (
        calculate_accuracy !== 0 &&
        calculate_accuracy_unit !== 0 &&
        calculate_accuracy !== undefined &&
        calculate_accuracy_unit !== undefined
      ) {
        setSeniorAndGetOptions();
      }
    }
  }, []);

  useEffect(() => {
    app_id && event_id && getDataSources(app_id, product_id, event_id);
  }, [app_id, product_id, event_id]);

  useEffect(() => {
    if (props.value) {
      getCalculateField(props.value.calculate_type_id);
    }
  }, [props.value && props.value.calculate_type_id]);

  // 获取数据源
  function getDataSources(app_id, product_id, event_id) {
    services.indexDataSource.relation({ app_id: app_id || undefined, product_id: product_id || undefined, event_id: event_id || undefined }).then((res) => {
      if (res.code === 0) {
        setDataSources(res.data);
      }
    });
  }

  // 改变appId,EventId的回调
  function onAppOrEventIdHandleChange(type, id) {
    let data_source_type = form.getFieldValue('data_source_type');
    if (data_source_type === DATA_SOURCE_TYPE._COMSTOM) {
      let app_id = type === 'app_id' ? id : appId;
      let product_id = type === 'product_id' ? id : productId;
      let event_id = type === 'event_id' ? id : eventId;
      getDataSources(app_id, product_id, event_id);
      form.setFieldsValue({ data_source_id: '' }); // 清空数据源
    }
    clearOtherAttr();
  }

  const dataSourceTypeHandle = (e) => {
    if (e.target.value === DATA_SOURCE_TYPE._COMSTOM) {
      let app_id = form.getFieldValue('app_id');
      let product_id = form.getFieldValue('product_id');
      let event_id = form.getFieldValue('event_id');
      getDataSources(app_id, product_id, event_id);
    }
  };

  // 清空计算方式、计算字段、主属性、从属性
  function clearOtherAttr() {
    form.setFieldsValue({ calculate_field: '', main_field: '', sec_field: '' });
    setCondition(
      props.value && props.value.condition_type && props.value.condition_type === CONDITION_TYPE._CONFIG
        ? props.value.conditions
        : []
    );
  }

  // 获取计算方式
  function getCalculate() {
    services.computeMode.getCodeList({}).then((res) => {
      if (res.code === 0) {
        setCalculate(res.data);
      }
    });
  }

  // 通过id获取计算方式的remark
  function getCalculateRemarkByCode(id) {
    const currentCalculate = calculate.find((it) => it.calculate_type_id === id);
    currentCalculate && setCalculateRemark(currentCalculate.remark);
  }

  /** @method setSeniorAndGetOptions
   *  @description 获取是否展示高级选项，并设置高级选项的options
   *  @param {Boolean} isOnlySenior 默认true, true->是点击高级选项时调用， false->时间范围单位onChange时调用
   *  @param {String} value onchange时的监听值
   * */

  function setSeniorAndGetOptions(isOnlySenior = true, value) {
    // 击高级选项时调用
    if (isOnlySenior) {
      setSenior(!senior); // toggle 展示、隐藏
      // 如果date_range_unit已经有值，则需要获取到精度的时间范围
      if (!senior) {
        const value = form.getFieldValue('date_range_unit');
        if (value) {
          const accuracyUnitTime = getChildTimeUnit(value, time_codes);
          setAccuracyUnit(accuracyUnitTime);
        }
      }
      // 时间范围单位onChange时调用
    } else {
      // 如果高级选项已经打开，才进行下列的判断，
      if (senior) {
        const accuracyUnitTime = getChildTimeUnit(value, time_codes);
        // 如果获取到精度的时间范围长度为0，则隐藏高级选项，
        if (accuracyUnitTime.length === 0) {
          setSenior(false);
        }
        setAccuracyUnit(accuracyUnitTime);
        form.setFieldsValue({ calculate_accuracy_unit: '' }); // 清空calculate_accuracy_unit
      }
      // 新增，针对苏州农商行
      if (NATURE_TIME_KEYS.includes(value)) {
        setIsNature(true);
      } else {
        setIsNature(false);
      }
    }
  }

  /** @method validateMultiple
   *  @description 验证倍数
   *  @param {Number} value  数值
   *  @param {String} unit  数值
   *  @param {Number} multiple 倍数
   *  @return {Number} 1/0/2
   *  向上取整(时间范围换算出来的秒数 / (value*unit)换算出来的秒数) > 倍数(multiple),返回1
   *  向上取整(时间范围换算出来的秒数 / (value*unit)换算出来的秒数） <= 倍数(multiple),返回0
   *  时间范围换算出来的秒数 - (value*unit)换算出来的秒数 < 0,返回2
   * */
  // function validateMultiple(value, unit, multiple) {
  //   const date_range_unit = form.getFieldValue('date_range_unit'); // 时间范围的单位
  //   const date_range = form.getFieldValue('date_range'); // 时间范围的数值
  //   const date_range_seconds = getSeconds(date_range_unit, time_codes, date_range); // 时间范围换算出来的秒数
  //   const current_seconds = getSeconds(unit, time_codes, value); //当前需要验证的单位*数值换算出来的秒数（主要应用在连续时间、计算精度）
  //   if (date_range_seconds === 0 || current_seconds === 0) {
  //     return 1;
  //   }
  //   if (date_range_seconds - current_seconds < 0) {
  //     return 2;
  //   }
  //   if (Math.ceil(date_range_seconds / current_seconds) > multiple) {
  //     return 0;
  //   } else {
  //     return 1;
  //   }
  // }

  // 计算精度
  function validateCalulateAccuracy(rule, value, callback) {
    // const result = validateMultiple(value, form.getFieldValue('calculate_accuracy_unit'), 365);
    if (!value && form.getFieldValue('calculate_accuracy_unit')) {
      callback('请填写计算精度');
    } else {
      callback();
    }
    //苏州银行放开限制
    // if (result === 0) {
    //   callback('时间范围不能大于计算精度的365倍');
    // } else if (result === 2) {
    //   callback('计算精度不能大于时间范围');
    // } else {
    //   callback();
    // }
  }

  const getAllPreviewData = () => {
    const values = form.getFieldsValue();
    const time = values.date_range ? <span style={{ color: '#ff2f92' }}>{values.date_range}</span> : '';
    const time_unit = values.date_range_unit ? (
      <span style={{ color: '#ff2f92', margin: '2px 5px' }}>
        {time_codes.find((it) => it.key === values.date_range_unit)
          ? time_codes.find((it) => it.key === values.date_range_unit).value
          : ''}
      </span>
    ) : (
      ''
    );
    const calc = values.calculate_type_id ? (
      <span style={{ color: '#009193', margin: '2px 5px' }}>
        {calculate.find((it) => it.calculate_type_id === values.calculate_type_id)
          ? calculate.find((it) => it.calculate_type_id === values.calculate_type_id).calculate_type_name
          : ''}
      </span>
    ) : (
      ''
    );
    const calc_field = values.calculate_field ? (
      <span style={{ color: '#0433ff', margin: '2px 5px' }}>
        {variable.field.find((it) => it.field_id === values.calculate_field)
          ? variable.field.find((it) => it.field_id === values.calculate_field).name
          : ''}
      </span>
    ) : (
      ''
    );
    const main_field = values.main_field ? (
      <span style={{ color: '#0433ff', margin: '2px 5px' }}>
        {variable.field.find((it) => it.field_id === values.main_field)
          ? variable.field.find((it) => it.field_id === values.main_field).name
          : ''}
      </span>
    ) : (
      ''
    );
    const sec_field = values.sec_field ? (
      <span style={{ color: '#0433ff', margin: '2px 5px' }}>
        {variable.field.find((it) => it.field_id === values.sec_field)
          ? variable.field.find((it) => it.field_id === values.sec_field).name
          : ''}
      </span>
    ) : (
      ''
    );
    return {
      data: () => {
        return (
          <>
            {time}
            {time_unit}
            {main_field}
            {sec_field}
            {calc}
            {calc_field}
          </>
        );
      },
      conditions,
    };
  };

  // 提交
  const handleSubmit = (e) => {
    e.preventDefault();
    form.validateFields((err, values) => {
      const action = props.actionType === 'add' || props.actionType === 'copy' ? 'add' : 'update';
      if (!err) {
        const params = {
          data_source_type: 1,
          ...values,
          is_contains_this: values.is_contains_this ? 1 : 0,
          is_history: values.is_history ? 1 : 0,
          calculate_accuracy: values.calculate_accuracy ? values.calculate_accuracy : 0,
          calculate_accuracy_unit: values.calculate_accuracy_unit ? values.calculate_accuracy_unit : 0,
        };
        if (params.sec_field === undefined) {
          params.sec_field = '';
        }
        try {
          if (values.condition_type === CONDITION_TYPE._CONFIG) {
            params.conditions = getConditionGroupJson(conditions); //验证配置的条件组json
          } else if (values.condition_type === CONDITION_TYPE._SQ) {
            params.conditions = conditionText;
          }
          if (props.actionType === 'update') {
            params.status = values.status ? ENABLE_STATUS._TRUE : ENABLE_STATUS._FALSE;
            params.feature_id = props.value.feature_id;
          }
          services.indicator[action](params).then((data) => {
            if (data.code === 0) {
              message.success(data.msg);
              if (props.closeModal) {
                props.closeModal();
              }
            } else {
              message.error(data.msg);
            }
          });
        } catch (err) {
          message.warning(err);
          return false;
        } finally {
          console.log('验证了');
        }
      }
    });
  };

  // condition onChange回调
  const handleConditionChange = (e) => {
    if (form.getFieldValue('condition_type') === CONDITION_TYPE._CONFIG) {
      setCondition(e);
    } else if (form.getFieldValue('condition_type') === CONDITION_TYPE._SQ) {
      setConditionText(e);
    }
  };

  // 在calculate列表中查询calculate_type_id===id的当前对象的code
  const getCalculateCode = (id) => {
    const cur = calculate.find((item) => item.calculate_type_id === id);
    return cur ? cur.calculate_type_code : null;
  };

  function getCalculateField(id) {
    const cur = calculate.find((item) => item.calculate_type_id === id);
    if (cur === undefined) {
      setCalculateField(variable.field);
    }
    const field = variable.field.filter((item) => {
      return cur.calculate_field_type.split(',').includes(item.data_type);
    });
    setCalculateField(field);
  }

  const handleConditionType = (e) => {
    setConditionType(e.target.value);
  };

  const handleIsExecCondition = () => {
    setConditionType(CONDITION_TYPE._CONFIG);
  };

  const formItems_base = [
    {
      label: {
        label: '指标名称',
        className: 'tantuer-form-item3',
      },
      name: 'feature_name',
      options: {
        initialValue: feature_name,
        rules: [
          { required: true, message: '请输入指标名称' },
          { max: 128, message: '最长128个字符' },
          { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
        ],
      },
      component: (
        <Input
          placeholder='请填写'
          disabled={props.actionType === 'detail'}
          style={{ ...compare(props, 'feature_name') }}
        />
      ),
    },

    {
      label: {
        label: '数据源来源',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'data_source_type',
      options: {
        initialValue: data_source_type || 1,
        rules: [{ required: true }],
      },
      component: (
        <Radio.Group
          onChange={dataSourceTypeHandle}
          style={compare(props, 'data_source_type')}
          disabled={props.actionType !== 'add' && props.actionType !== 'copy'}
        >
          <Radio value={1}>风控事件</Radio>
          <Radio value={2}>自定义</Radio>
        </Radio.Group>
      ),
    },

    ...items,
    form.getFieldValue('data_source_type') === DATA_SOURCE_TYPE._COMSTOM && {
      label: {
        label: '数据源',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'data_source_id',
      options: {
        initialValue: (props.isImportant ? source_name : data_source_id) || '',
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Select
          style={{ ...compare(props, 'data_source_id') }}
          disabled={props.actionType !== 'add' && props.actionType !== 'copy'}
        >
          {dataSources
            .filter((it) => it.data_source_id !== -1)
            .map((it) => {
              return (
                <Select.Option value={it.data_source_id} key={it.data_source_id}>
                  {it.source_name}
                </Select.Option>
              );
            })}
        </Select>
      ),
    },
    props.actionType === 'update'
      ? {
          label: {
            label: '是否启用',
            className: 'tantuer-form-item3',
          },
          name: 'status',
          options: {
            valuePropName: 'checked',
            initialValue: status === ENABLE_STATUS._TRUE ? true : false,
          },
          component: <Switch disabled={props.actionType === 'detail'} />,
        }
      : false,
    {
      label: {
        label: '描述',
        className: props.actionType === 'update' ? 'tantuer-form-item3' : 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'remark',
      options: {
        initialValue: remark || '',
        rules: [{ max: 256, message: '最长256个字符' }],
      },
      component: (
        <Input placeholder='描述' disabled={props.actionType === 'detail'} style={{ ...compare(props, 'remark') }} />
      ),
    },
  ].filter(Boolean);

  const formItems_conditions1 = [
    {
      label: {
        label: '时间范围',
        className: 'tantuer-form-item3 tantuer-form-item-200',
      },
      name: 'date_range',
      options: {
        initialValue: date_range || 1,
        rules: [
          { required: true, message: '请输入时间范围' },
          {
            validator: (rule, value, callback) => {
              form.validateFields(['calculate_accuracy']);
              callback();
            },
          },
        ],
      },
      component: (
        <InputNumber
          min={1}
          step={1}
          disabled={props.actionType === 'detail'}
          parser={(value) => value.replace(/\./g, '')}
          style={compare(props, 'date_range')}
        />
      ),
    },
    {
      name: 'date_range_unit',
      className: 'tantuer-form-item3 ',
      options: {
        initialValue: date_range_unit,
        rules: [{ required: true, message: '请选择时间单位' }],
      },
      component: (
        <Select
          style={{ width: '120px', ...compare(props, 'date_range_unit') }}
          disabled={props.actionType === 'detail'}
          onChange={(value) => setSeniorAndGetOptions(false, value)}
        >
          {time_codes.map((it) => {
            return (
              <Select.Option value={it.key} key={it.key}>
                {it.value}
              </Select.Option>
            );
          })}
        </Select>
      ),
      after: (
        <>
          <Button type='link' disabled={props.actionType === 'detail'} onClick={() => setSeniorAndGetOptions()}>
            高级选项 {!senior ? <Icon type='down' /> : <Icon type='up' />}
          </Button>

          {isNature && (
            <>
              {form.getFieldDecorator('is_history', {
                initialValue: is_history === GLOBAL_TRUE_FALSE._TRUE ? true : false,
                valuePropName: 'checked',
              })(<Checkbox disabled={props.actionType === 'detail'} />)}
              <span style={{ marginLeft: '5px' }}>不含当前时间段</span>
            </>
          )}
        </>
      ),
    },
  ];
  const formItems_accuracy = [
    {
      label: {
        label: '计算精度',
        className: 'tantuer-form-item3 error-length3',
      },
      name: 'calculate_accuracy',
      options: {
        initialValue: calculate_accuracy || '',
        rules: [
          {
            validator: validateCalulateAccuracy,
          },
        ],
      },
      component: (
        <InputNumber
          min={1}
          step={1}
          disabled={props.actionType === 'detail'}
          style={compare(props, 'calculate_accuracy')}
        />
      ),
    },
    {
      name: 'calculate_accuracy_unit',
      options: {
        initialValue: accuracyUnit.length > 0 ? calculate_accuracy_unit || '' : '',
        rules: [
          {
            validator: (rule, value, callback) => {
              if (!value && form.getFieldValue('calculate_accuracy')) {
                callback('请选择计算精度单位');
              } else {
                form.validateFields(['calculate_accuracy']);
                callback();
              }
            },
          },
        ],
      },
      component: (
        <Select
          style={{ width: '120px', ...compare(props, 'calculate_accuracy_unit') }}
          disabled={props.actionType === 'detail'}
        >
          {accuracyUnit.map((it) => {
            return (
              <Select.Option value={it.key} key={it.key}>
                {it.value}
              </Select.Option>
            );
          })}
        </Select>
      ),
      after: (
        <Question
          title={
            <>
              指标计算数据按计算精度进行存储，计算精度越小，计算更精确，当然计算量也越大；
              计算精度为非必填项，如您已了解可自行设置，否则按系统默认值即可。
            </>
          }
        />
      ),
    },
  ];
  const formItems_calculate = [
    {
      label: {
        label: '计算方式',
        className: 'tantuer-form-item3',
        extra: calculateRemark,
      },
      name: 'calculate_type_id',
      options: {
        initialValue: calculate_type_id,
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Select
          style={{ width: '250px', ...compare(props, 'calculate_type_id') }}
          disabled={props.actionType === 'detail'}
          showSearch
          showArrow={true}
          onChange={(value) => getCalculateRemarkByCode(value)}
          filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
        >
          {calculate.map((it) => {
            return (
              <Select.Option
                value={it.calculate_type_id}
                key={it.calculate_type_id}
                disabled={props.actionType === 'detail'}
              >
                {it.calculate_type_name}
              </Select.Option>
            );
          })}
        </Select>
      ),
      after: (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          {// 苏州银行新增，趋势统计\趋势最大次数统计
          (getCalculateCode(form.getFieldValue('calculate_type_id')) === 'trend_count' ||
            getCalculateCode(form.getFieldValue('calculate_type_id')) === 'trend_max_count') && (
            <>
              {form.getFieldDecorator('trend_direction', {
                initialValue:
                  trend_direction !== undefined && trend_direction !== '' ? trend_direction : 'increase_trend',
                rules: [{ required: true, message: '请选择' }],
              })(
                <Select style={{ width: '120px' }} disabled={props.actionType === 'detail'}>
                  <Select.Option value={'increase_trend'}>趋势递增</Select.Option>
                  <Select.Option value={'decrease_trend'}>趋势递减</Select.Option>
                  <Select.Option value={'level_trend'}>趋势水平</Select.Option>
                </Select>
              )}
            </>
          )}
          {!CALCULATE_CODE_GROUP.includes(getCalculateCode(form.getFieldValue('calculate_type_id'))) && ( // 大多数情况
            <>
              {form.getFieldDecorator('is_contains_this', {
                initialValue: is_contains_this === GLOBAL_TRUE_FALSE._TRUE ? true : false,
                valuePropName: 'checked',
              })(<Checkbox disabled={props.actionType === 'detail'} />)}
              <span style={{ ...compare(props, 'is_contains_this'), marginLeft: '5px' }}>计算包括本次请求</span>
              <Question
                title={
                  <>
                    <div>
                      如指标名为“近一天累计转账次数”，勾选后本次转账请求算入转账总次数，否则转账总次数不包含本次请求
                    </div>
                  </>
                }
              />
            </>
          )}
          {getCalculateCode(form.getFieldValue('calculate_type_id')) === 'history_value' && ( // 历史指标
            <>
              近
              <Form.Item style={{ margin: 0 }}>
                {form.getFieldDecorator('limit_count', {
                  initialValue: limit_count,
                })(
                  <InputNumber
                    min={0}
                    max={100000000}
                    step={1}
                    style={{ width: '100px', margin: '0 5px', ...compare(props, 'limit_count') }}
                    disabled={props.actionType === 'detail'}
                  />
                )}
              </Form.Item>
              次/笔
            </>
          )}
          {getCalculateCode(form.getFieldValue('calculate_type_id')) === 'frequency' && ( // 频次排行
            <>
              {form.getFieldDecorator('sort_type', {
                initialValue: sort_type !== undefined && sort_type !== 0 ? sort_type : 1,
                rules: [{ required: true, message: '请选择' }],
              })(
                <Select
                  style={{ width: '80px', ...compare(props, 'sort_type') }}
                  disabled={props.actionType === 'detail'}
                >
                  <Select.Option value={1}>正序</Select.Option>
                  <Select.Option value={2}>倒序</Select.Option>
                </Select>
              )}
              <span style={{ marginLeft: '5px' }}>排行前</span>
              <Form.Item style={{ margin: 0 }}>
                {form.getFieldDecorator('limit_count', {
                  initialValue: limit_count || 1,
                  rules: [{ required: true, message: '请填写' }],
                })(
                  <InputNumber
                    min={1}
                    max={9}
                    step={1}
                    style={{ width: '60px', margin: '0 5px', ...compare(props, 'limit_count') }}
                    disabled={props.actionType === 'detail'}
                  />
                )}
              </Form.Item>
            </>
          )}
        </div>
      ),
    },
  ];
  const formItems_continue = [
    getCalculateCode(form.getFieldValue('calculate_type_id')) === 'continue_count'
      ? {
          label: {
            label: '连续时间',
            className: 'tantuer-form-item3',
          },
          name: 'duration_time',
          options: {
            initialValue: duration_time || 1,
            rules: [{ required: true, message: '请输入时间范围' }],
          },
          component: (
            <InputNumber
              min={1}
              step={1}
              disabled={props.actionType === 'detail'}
              parser={(value) => value.replace(/\./g, '')}
              style={compare(props, 'duration_time')}
            />
          ),
        }
      : false,
    getCalculateCode(form.getFieldValue('calculate_type_id')) === 'continue_count'
      ? {
          name: 'duration_time_unit',
          options: {
            initialValue: duration_time_unit || undefined,
            rules: [{ required: true, message: '请选择时间单位' }],
          },
          component: (
            <Select
              style={{ width: '120px', ...compare(props, 'duration_time_unit') }}
              disabled={props.actionType === 'detail'}
            >
              {time_codes.map((it) => {
                return (
                  <Select.Option value={it.key} key={it.key}>
                    {it.value}
                  </Select.Option>
                );
              })}
            </Select>
          ),
        }
      : false,
  ].filter(Boolean);
  const formItems_conditions2 = [
    getCalculateCode(form.getFieldValue('calculate_type_id')) !== 'count'
      ? {
          label: {
            label: '计算字段',
            className: 'tantuer-form-item3',
          },
          name: 'calculate_field',
          options: {
            initialValue: (props.isImportant ? calculate_field_name : calculate_field) || undefined,
            rules: [{ required: true, message: '请选择' }],
          },
          component: (
            <Select
              style={{ width: 250, ...compare(props, 'calculate_field') }}
              disabled={props.actionType === 'detail'}
              showSearch
              showArrow={true}
              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              {variable.field.map((it) => {
                return (
                  <Select.Option value={it.field_id} key={it.field_id}>
                    {it.name}
                  </Select.Option>
                );
              })}
            </Select>
          ),
        }
      : false,
    {
      label: {
        label: '主属性',
        className: 'tantuer-form-item3',
      },
      name: 'main_field',
      options: {
        initialValue: (props.isImportant ? main_field_name : main_field) || undefined,
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Select
          style={{ width: '250px', ...compare(props, 'main_field') }}
          disabled={props.actionType === 'detail'}
          showSearch
          showArrow={true}
          filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
        >
          {variable.field.map((it) => {
            return (
              <Select.Option value={it.field_id} key={it.field_id}>
                {it.name}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
    {
      label: {
        label: '从属性',
        className: 'tantuer-form-item3',
      },
      name: 'sec_field',
      options: {
        initialValue: (props.isImportant ? sec_field_name : sec_field) || undefined,
      },
      component: (
        <Select
          style={{ width: '250px', ...compare(props, 'sec_field') }}
          disabled={props.actionType === 'detail'}
          allowClear
          showSearch
          showArrow={true}
          filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
        >
          {variable.field.map((it) => {
            return (
              <Select.Option value={it.field_id} key={it.field_id}>
                {it.name}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
    {
      label: {
        label: '添加计算规则',
        className: 'tantuer-form-item3',
      },
      name: 'is_exec_condition',
      options: {
        initialValue: is_exec_condition,
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Radio.Group
          disabled={props.actionType === 'detail'}
          className={compareClass(props, 'is_exec_condition')}
          onChange={handleIsExecCondition}
        >
          <Radio value={IS_EXEC_CONDITION._TRUE}>是</Radio>
          <Radio value={IS_EXEC_CONDITION._FALSE}>否</Radio>
        </Radio.Group>
      ),
    },
  ].filter(Boolean);

  const formItems_conditions3 = [
    {
      label: {
        label: '条件类型',
        className: 'tantuer-form-item3',
      },
      name: 'condition_type',
      options: {
        initialValue: condition_type || CONDITION_TYPE._CONFIG,
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Radio.Group
          onChange={handleConditionType}
          disabled={props.actionType === 'detail'}
          className={compareClass(props, 'condition_type')}
        >
          <Radio.Button value={CONDITION_TYPE._CONFIG}>自定义</Radio.Button>
          <Radio.Button value={CONDITION_TYPE._SQ}>groovy脚本</Radio.Button>
        </Radio.Group>
      ),
    },
  ];

  return (
    <div className='tantuer-form'>
      <Form onSubmit={() => false} className='login-form'>
        <div className='tantuer-field-area'>
          <div className='form-title'>基本属性</div>
          <Row type='flex' gutter={20}>
            {formItems_base.map((item) => {
              return (
                <Col span={12} key={item.name}>
                  <FormItem {...props} form={form} item={item} colNum={2} />
                </Col>
              );
            })}
          </Row>
        </div>
        <Divider />

        <div className='tantuer-field-area'>
          <div className='form-title'>条件配置</div>
          <Row type='flex'>
            <Col span={17}>
              <Row type='flex' className='tantuer-form-item3 tantuer-form-item-nowrap tantuer-form-item-200'>
                <Col span={18} className='flex-1'>
                  <Row type='flex' gutter={10}>
                    {formItems_conditions1.map((item) => {
                      return (
                        <Col span={7} key={item.name}>
                          <FormItem {...props} form={form} item={item} colNum={1} />
                        </Col>
                      );
                    })}
                  </Row>
                </Col>
              </Row>
              {senior && (
                <Row type='flex' className='tantuer-form-item3 tantuer-form-item-nowrap'>
                  <Col span={18} className='flex-1'>
                    <Row type='flex' gutter={10}>
                      {formItems_accuracy.map((item) => {
                        return (
                          <Col span={7} key={item.name}>
                            <FormItem {...props} form={form} item={item} colNum={1} />
                          </Col>
                        );
                      })}
                    </Row>
                  </Col>
                </Row>
              )}

              <Row type='flex'>
                {formItems_calculate.map((item) => {
                  return (
                    <Col span={24} key={item.name}>
                      <FormItem {...props} form={form} item={item} colNum={1} />
                    </Col>
                  );
                })}
                {formItems_continue.map((item) => {
                  return (
                    <Col key={item.name}>
                      <FormItem {...props} form={form} item={item} colNum={1} />
                    </Col>
                  );
                })}
                {formItems_conditions2.map((item) => {
                  return (
                    <Col span={24} key={item.name}>
                      <FormItem {...props} form={form} item={item} colNum={1} />
                    </Col>
                  );
                })}
              </Row>
            </Col>
            <Col span={7}>
              <Preview
                code={getCalculateCode(form.getFieldValue('calculate_type_id'))}
                previewData={getAllPreviewData()}
              />
            </Col>
          </Row>
          {form.getFieldValue('is_exec_condition') === IS_EXEC_CONDITION._TRUE && (
            <>
              <Row type='flex'>
                {formItems_conditions3.map((item) => {
                  return (
                    <Col span={24} key={item.name}>
                      <FormItem {...props} form={form} item={item} colNum={1} />
                    </Col>
                  );
                })}
              </Row>
              <div style={{ padding: '0 10px' }}>
                <AddConditions
                  {...props}
                  type={contitionType}
                  value={conditions}
                  compareData={
                    (props.compareData && props.compareData.conditions && props.compareData.conditions) || []
                  }
                  conditionText={conditionText}
                  variable={variable}
                  using_variables={using_variables}
                  disabled={props.actionType === 'detail'}
                  onChange={handleConditionChange}
                />
              </div>
            </>
          )}
        </div>
        {props.actionType !== 'detail' && (
          <div className='form-btn'>
            <Button type='primary' onClick={handleSubmit} className='login-form-button' autoFocus={true}>
              确定
            </Button>
            <Button className='login-form-button' onClick={() => props.closeModal && props.closeModal(true)}>
              取消
            </Button>
          </div>
        )}
      </Form>
    </div>
  );
}
function mapStateToProps(state) {
  return {
    window_time_unit: state.code.window_time_unit,
  };
}
export default connect(mapStateToProps)(Form.create()(IndicatorAdd));
